package com.ys.peony.ui.fragment;

import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.megvii.idcardlib.IDCardScanActivity;
import com.megvii.idcardquality.bean.IDCardAttr;
import com.megvii.livenesslib.LivenessActivity;
import com.ys.peony.R;
import com.ys.peony.app.Cache;
import com.ys.peony.app.HttpURL;
import com.ys.peony.app.YSConstant;
import com.ys.peony.base.BaseFragment;
import com.ys.peony.enums.FaceOCRErrorEnum;
import com.ys.peony.enums.IDCardOCRErrorEnum;
import com.ys.peony.http.JCHttpManagerUtils;
import com.ys.peony.http.base.BaseRespCallBack;
import com.ys.peony.model.CustomerInfoModel;
import com.ys.peony.model.DaimianshenModel;
import com.ys.peony.model.FaceModelResp;
import com.ys.peony.model.IDCardFrontModel;
import com.ys.peony.model.UserModel;
import com.ys.peony.ui.activity.DocumentsReviewActivity;
import com.ys.peony.ui.view.IdCardDialog;
import com.ys.peony.utils.FileUtils;
import com.ys.peony.utils.ImageLoadUtils;
import com.ys.peony.utils.JSONUtil;
import com.ys.peony.utils.LoadingProgressUtils;
import com.ys.peony.utils.NetUtils;
import com.ys.peony.utils.SharePreferencesUtils;
import com.ys.peony.utils.StringUtils;
import com.ys.peony.utils.ToastUtils;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by yukang on 2017/9/13.
 */

public class FaceFragment extends BaseFragment implements View.OnClickListener, IdCardDialog.MyClickListener {

    //正面
    public static final String ID_CARD_FRONT = "idcard_front.jpg";
    //背面
    public static final String ID_CARD_BACK = "idcard_back.jpg";
    //脸部
    public static final String FACE_PHOTOS = "face.jpg";
    private static final int FONT_IDCARD = 1;
    private static final int BACK_IDCARD = 2;
    private static final int FACE = 3;

    //证件识别
    public static final int INTO_IDCARDSCAN_PAGE = 100;
    //人脸识别
    public static final int PAGE_INTO_LIVENESS = 200;

    @BindView(R.id.IB_IDCard_Positive)
    ImageButton imageButtonIDCardPositive;
    @BindView(R.id.IB_IDCard_Reverse)
    ImageButton imageButtonIDCardReverse;
    @BindView(R.id.IB_Head_Portrait)
    ImageButton imageButtonHeadPortrait;
    @BindView(R.id.iv_lock)
    ImageView iv_lock;

    private String loanId;//业务ID
    private String clientId;//客户主键
    private String clientInfoId;//客户资料主键
    private String clientName;//姓名
    private String idCard;//身份证号
    private boolean frontExists = false;//正面
    private boolean backExists = false;//反面
    private IDCardAttr.IDCardSide mIDCardSide;
    private MediaPlayer mMediaPlayer = null;
    //人脸识别成功返回实体对象
    private String delta;
    private int mPageType = YSConstant.INVALID;//当前页面标记 1：自己 2：配偶


    @Override
    public int getLayoutRes() {
        return R.layout.fragment_face;
    }

    @Override
    public void initView() {
        //删除身份证人脸识别相关缓存
        FileUtils.doDeleteFile(Cache.FACE_MODULE);
        imageButtonIDCardPositive.setOnClickListener(this);
        imageButtonIDCardReverse.setOnClickListener(this);
        imageButtonHeadPortrait.setOnClickListener(this);
        iv_lock.setOnClickListener(this);
        initData();

    }

    private void initData() {
        Intent intent = getActivity().getIntent();
        if (intent != null) {
            loanId = intent.getStringExtra("loanId");
            clientId = intent.getStringExtra("clientId");
            clientName = intent.getStringExtra("clientName");
            idCard = intent.getStringExtra("idCard");
            DaimianshenModel daimianshenModel = (DaimianshenModel) intent.getSerializableExtra("daimianshenmodel");
            if (daimianshenModel != null) {
                List<DaimianshenModel.BusiLoanInfo> infos = daimianshenModel.getBusiLoanInfoList();
                if (infos != null) {
                    String front = "";
                    String back = "";
                    String face = "";
                    for (int i = 0; i < infos.size(); i++) {
                        if (mPageType == DocumentsReviewActivity.OTHER_TYPE) {
                            if (infos.get(i).getPath().contains("front_other.jpg")) {
                                front = HttpURL.IMG_URL + infos.get(i).getPath();
                            } else if (infos.get(i).getPath().contains("back_other.jpg")) {
                                back = HttpURL.IMG_URL + infos.get(i).getPath();
                            } else if (infos.get(i).getPath().contains("face_other.jpg")) {
                                face = HttpURL.IMG_URL + infos.get(i).getPath();
                            }
                        } else {
                            if (infos.get(i).getPath().contains("front_main.jpg")) {
                                front = HttpURL.IMG_URL + infos.get(i).getPath();
                            } else if (infos.get(i).getPath().contains("back_main.jpg")) {
                                back = HttpURL.IMG_URL + infos.get(i).getPath();
                            } else if (infos.get(i).getPath().contains("face_main.jpg")) {
                                face = HttpURL.IMG_URL + infos.get(i).getPath();
                            }
                            if(!TextUtils.isEmpty(front) && !TextUtils.isEmpty(back) && !TextUtils.isEmpty(face)) {
                                ((DocumentsReviewActivity)getActivity()).setMainFinish(true);
                            } else {
                                ((DocumentsReviewActivity)getActivity()).setMainFinish(false);
                            }
                        }
                    }
                    if (!TextUtils.isEmpty(front) && !TextUtils.isEmpty(back) && !TextUtils.isEmpty(face)) {
                        ImageLoadUtils.showImg(imageButtonIDCardPositive, front, false);
                        ImageLoadUtils.showImg(imageButtonIDCardReverse, back, false);
                        ImageLoadUtils.showImg(imageButtonHeadPortrait, face, false);
                        imageButtonIDCardPositive.setOnClickListener(null);
                        imageButtonIDCardReverse.setOnClickListener(null);
                        imageButtonHeadPortrait.setOnClickListener(null);
                        iv_lock.setVisibility(View.GONE);

                    }
                }
            }

        }
        //获取用户ID
        getClientInformation();
    }

    @Override
    public void onClick(View v) {
        if (!((DocumentsReviewActivity) getActivity()).getAuthorResult()) {
            ToastUtils.showToast("联网授权失败");
            return;
        }
        switch (v.getId()) {
            case R.id.IB_IDCard_Positive: {
                if(!((DocumentsReviewActivity)getActivity()).isMainFinish() && mPageType == DocumentsReviewActivity.OTHER_TYPE) {
                    ToastUtils.showToast("请先进行主借人身份验证");
                    return;
                }
                //身份证正面扫描
                if (StringUtils.isEmpty(clientInfoId)) {
                    ToastUtils.showToast("业务ID为空");
                    return;
                }
                Intent intent = new Intent(getContext(), IDCardScanActivity.class);
                intent.putExtra("side", 0);
                intent.putExtra("isvertical", false);
                startActivityForResult(intent, INTO_IDCARDSCAN_PAGE);
                break;
            }
            case R.id.IB_IDCard_Reverse: {//身份证反面
                if (!frontExists) {
                    ToastUtils.showToast("请先扫描身份证正面");
                    return;
                }
                Intent intent = new Intent(getContext(), IDCardScanActivity.class);
                intent.putExtra("side", 1);
                intent.putExtra("isvertical", false);
                startActivityForResult(intent, INTO_IDCARDSCAN_PAGE);
                break;
            }
            case R.id.IB_Head_Portrait: {//人脸
                doFaceVerify();
                break;
            }
            case R.id.iv_lock: {
                if (!frontExists || !backExists) {
                    ToastUtils.showToast("请先扫描身份证正反面");
                    return;
                }
                showDialog();
                break;
            }
            default:
                break;
        }
    }

    private void doFaceVerify() {
        if (!frontExists || !backExists) {
            ToastUtils.showToast("请先扫描身份证正反面");
            return;
        }
        Intent intent = new Intent(getContext(), LivenessActivity.class);
        startActivityForResult(intent, PAGE_INTO_LIVENESS);
    }


    /**
     * describe:获取用户ID
     * author:zhangcong
     * date:2017/6/4 17:40
     */
    private void getClientInformation() {
        if (!NetUtils.isNetworkConnected(getContext())) {
            ToastUtils.showToast(getResources().getString(R.string.no_net_error));
            return;
        }
        LoadingProgressUtils.showProgressDialog(getContext());
        final JCHttpManagerUtils httpManagerUtils = new JCHttpManagerUtils();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("loanId", loanId);
        params.put("info_id", YSConstant.USER_INFO_ID);
        httpManagerUtils.get(HttpURL.getClientInformation, params, new BaseRespCallBack() {
            @Override
            public void onRespSuccess(String respStr) {
                if (StringUtils.isEmpty(respStr)) {
                    showTip("用户信息返回为空");
                } else {
                    CustomerInfoModel customerInfoModel = JSONUtil.parseObject(respStr, CustomerInfoModel.class);
                    clientInfoId = customerInfoModel.getId();
                }
            }
        });
    }

    /**
     * 显示照片
     */
    public void showImage(int type) {
        switch (type) {
            case FONT_IDCARD:
                String frontPath = Cache.FACE_MODULE + File.separator + ID_CARD_FRONT;
                Bitmap frontBitmap = ImageLoadUtils.decodeScaleImage(frontPath,
                        imageButtonIDCardPositive.getMeasuredWidth(),
                        imageButtonIDCardPositive.getMeasuredHeight());
                if (frontBitmap != null) {
                    imageButtonIDCardPositive.setImageBitmap(frontBitmap);

                }
                break;
            case BACK_IDCARD:
                String backPath = Cache.FACE_MODULE + File.separator + ID_CARD_BACK;
                Bitmap backBitmap = ImageLoadUtils.decodeScaleImage(backPath,
                        imageButtonIDCardReverse.getMeasuredWidth(),
                        imageButtonIDCardReverse.getMeasuredHeight());
                if (backBitmap != null) {
                    imageButtonIDCardReverse.setImageBitmap(backBitmap);
                }

                break;
            case FACE:
                String facePath = Cache.FACE_MODULE + File.separator + FACE_PHOTOS;
                Bitmap bitmap = ImageLoadUtils.decodeScaleImage(facePath,
                        imageButtonHeadPortrait.getMeasuredWidth(),
                        imageButtonHeadPortrait.getMeasuredHeight());
                if (bitmap != null) {
                    imageButtonHeadPortrait.setImageBitmap(bitmap);
                }
                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_OK) {
            if (requestCode == INTO_IDCARDSCAN_PAGE) {//身份证识别
                mIDCardSide = data.getIntExtra("side", 0) == 0 ? IDCardAttr.IDCardSide.IDCARD_SIDE_FRONT
                        : IDCardAttr.IDCardSide.IDCARD_SIDE_BACK;
                byte[] imgByte = data.getByteArrayExtra("idcardImg");
                //保存
                if (mIDCardSide == IDCardAttr.IDCardSide.IDCARD_SIDE_FRONT) {
                    frontExists = false;
                    FileUtils.byte2File(imgByte, Cache.FACE_MODULE, ID_CARD_FRONT);
                } else {
                    backExists = false;
                    FileUtils.byte2File(imgByte, Cache.FACE_MODULE, ID_CARD_BACK);
                }
                iDCardOcr();
            }

            if (requestCode == PAGE_INTO_LIVENESS) {//人脸识别
                String resultOBJ = data.getStringExtra("result");
                if (!JSONUtil.isJsonFormat(resultOBJ)) {
                    ToastUtils.showToast("活体验证失败，请重新验证");
                    return;
                }
                try {
                    JSONObject result = JSONUtil.stringToJSon(resultOBJ);
                    int resID = result.getInteger("resultcode");
                    showTip(result.getString("result"));
                    if (resID == R.string.verify_success) {
                        doPlay(R.raw.meglive_success);
                    } else if (resID == R.string.liveness_detection_failed_not_video) {
                        doPlay(R.raw.meglive_failed);
                    } else if (resID == R.string.liveness_detection_failed_timeout) {
                        doPlay(R.raw.meglive_failed);
                    } else if (resID == R.string.liveness_detection_failed) {
                        doPlay(R.raw.meglive_failed);
                    } else {
                        doPlay(R.raw.meglive_failed);
                    }
                    //人脸识别返回对象
                    delta = result.getString("deltaCode");
                    byte[] imgByte = data.getByteArrayExtra("faceImg");
                    FileUtils.byte2File(imgByte, Cache.FACE_MODULE, FACE_PHOTOS);
                    if (!StringUtils.isEmpty(delta)) {
                        uploadOCRFaceImage();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /***********************************************身份证识别 start***************************************/
    private void iDCardOcr() {
        if (!NetUtils.isNetworkConnected(getContext())) {
            ToastUtils.showToast(getResources().getString(R.string.no_net_error));
            return;
        }
        LoadingProgressUtils.showProgressDialog(getContext());
        final JCHttpManagerUtils httpManagerUtils = new JCHttpManagerUtils();
        File file = getFileImage();
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("api_key", HttpURL.FACE_API_KEY)
                .addFormDataPart("api_secret", HttpURL.FACE_API_SECRET)
                .addFormDataPart("legality", YSConstant.LEGAL_CHECK_YES)
                .addFormDataPart("image", file.getName(), RequestBody.create(MediaType.parse("image/png"), file))
                .build();
        httpManagerUtils.post(HttpURL.IDcard, requestBody, new BaseRespCallBack() {
            @Override
            public void onRespSuccess(String respStr) {
                final IDCardFrontModel idCardFrontModel = JSONUtil.parseObject(respStr, IDCardFrontModel.class);
                if (null != idCardFrontModel) {
                    if (StringUtils.isEmpty(idCardFrontModel.getError())) {
                        checkIdCard(idCardFrontModel);
                    } else {
                        String errorInfo = IDCardOCRErrorEnum.getErrorInfo(idCardFrontModel.getError());
                        showTip(errorInfo);
                    }
                } else {
                    showTip("调用Face++接口返回参数为空");
                }
            }

            @Override
            public void onRespFailure(String msg) {
                super.onRespFailure(msg);
                ToastUtils.showToast(msg);
            }
        });
    }

    /**
     * describe:获取流文件
     * author:zhangcong
     * date:2017/6/4 19:54
     */
    private File getFileImage() {
        if (mIDCardSide == IDCardAttr.IDCardSide.IDCARD_SIDE_FRONT) {
            return new File(Cache.FACE_MODULE + File.separator + ID_CARD_FRONT);
        } else {
            return new File(Cache.FACE_MODULE + File.separator + ID_CARD_BACK);
        }
    }

    /**
     * describe:校验身份证信息
     * author:czhang
     * date:2017/6/10 17:29
     */
    private void checkIdCard(IDCardFrontModel idCardFrontModel) {
        if (null == idCardFrontModel) {
            showTip("身份证不能识别");
            return;
        }
        if (mIDCardSide == IDCardAttr.IDCardSide.IDCARD_SIDE_FRONT) {
            if (mPageType == DocumentsReviewActivity.MAIN_TYPE &&
                    (StringUtils.isEmpty(idCard) || !idCardFrontModel.getId_card_number().equals(idCard))) {
                showTip("身份证号不一致");
                return;
            }
            if (mPageType == DocumentsReviewActivity.OTHER_TYPE) {
                idCard = idCardFrontModel.getId_card_number();
            }
            frontExists = true;
            clientName = idCardFrontModel.getName();
            showImage(FONT_IDCARD);
        } else if (mIDCardSide == IDCardAttr.IDCardSide.IDCARD_SIDE_BACK) {
            backExists = true;
            showImage(BACK_IDCARD);
        }
    }

    /***********************************************身份证识别 End***************************************/
    private void showTip(final String errorInfo) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (!TextUtils.isEmpty(errorInfo)) {
                    ToastUtils.showToast(errorInfo);
                } else {
                    ToastUtils.showToast("身份识别未知错误");
                }
            }
        });
    }


    /*******************************************人脸识别 Start********************************************/
    /**
     * describe:人脸识别
     * author:yukang
     * date:2017/9/1 16:56
     */
    private void uploadOCRFaceImage() {
        if (!NetUtils.isNetworkConnected(getContext())) {
            ToastUtils.showToast(getResources().getString(R.string.no_net_error));
            return;
        }
        LoadingProgressUtils.showProgressDialog(getContext());
        final JCHttpManagerUtils httpManagerUtils = new JCHttpManagerUtils();
        File file = new File(Cache.FACE_MODULE + File.separator + FACE_PHOTOS);
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("api_key", HttpURL.FACE_API_KEY)
                .addFormDataPart("api_secret", HttpURL.FACE_API_SECRET)
                .addFormDataPart("face_image_type", "raw_image")//取值只为“meglive”、“facetoken”、“raw_image”、“meglive_flash” 四者之一
                .addFormDataPart("delta", delta)
                .addFormDataPart("image", file.getName(), RequestBody.create(MediaType.parse("image/*"), file))
                .addFormDataPart("idcard_name", clientName)
                .addFormDataPart("idcard_number", idCard)
                .addFormDataPart("comparison_type", "1");//“1”表示有源比对,“0”表示无源比对;
        RequestBody requestBody = builder.build();
        httpManagerUtils.post(HttpURL.faceVerify, requestBody, new BaseRespCallBack() {
            @Override
            public void onRespSuccess(String respStr) {
                final FaceModelResp faceModelResp = JSONUtil.parseObject(respStr, FaceModelResp.class);
                if (null != faceModelResp) {
                    if (StringUtils.isEmpty(faceModelResp.getError_message())) {
                        checkFace(faceModelResp);
                    } else {
                        String errorInfo = FaceOCRErrorEnum.getErrorInfo(faceModelResp.getError_message());
                        showTip(errorInfo);
                        showDialog();
                    }
                } else {
                    showTip("调用face++接口失败");
                }
            }

            @Override
            public void onRespFailure(String msg) {
                super.onRespFailure(msg);
                ToastUtils.showToast(msg);
            }
        });

    }

    /**
     * describe:检查人脸
     * author:czhang
     * date:2017/6/19 21:37
     */
    private void checkFace(FaceModelResp faceModelResp) {
        String resultFaceId = faceModelResp.getResult_faceid();
        JSONObject jsonObject = JSONUtil.stringToJSon(resultFaceId);
        float confidence = jsonObject.getFloat("confidence").floatValue();
        JSONObject thresholdsJson = JSONUtil.stringToJSon(jsonObject.getString("thresholds"));
        float level = thresholdsJson.getFloat("1e-5").floatValue();
        if (confidence >= level) {
            upload(JSONUtil.toJSON(faceModelResp));
        } else {
            showTip("与身份证不是同一人");
        }
    }

    /**
     * describe:上传人脸识别信息
     * author:czhang
     * date:2017/6/8 22:36
     */
    public void upload(final String remakes) {
        UserModel userModel = SharePreferencesUtils.getInstance().getUserModel();
        LoadingProgressUtils.showProgressDialog(getContext());
        final JCHttpManagerUtils httpManagerUtils = new JCHttpManagerUtils();
        String time = System.currentTimeMillis() + "";
        String frontName = time + "_" + "front" + "_" + (mPageType == DocumentsReviewActivity.MAIN_TYPE ? "main" : "other") + ".jpg";
        String backName =time + "_" + "back" + "_" + (mPageType == DocumentsReviewActivity.MAIN_TYPE ? "main" : "other") + ".jpg";
        String faceName = time + "_" + "face" + "_" + (mPageType == DocumentsReviewActivity.MAIN_TYPE ? "main" : "other") + ".jpg";
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("userId", userModel.getId())
                .addFormDataPart("loanId", loanId)
                .addFormDataPart("typeId", clientId)
                .addFormDataPart("clientInfoId", clientInfoId)
                .addFormDataPart("type", YSConstant.CLASS_CUSTOMER)
                .addFormDataPart("remakes", remakes)
                .addFormDataPart("files", frontName, RequestBody.create(MediaType.parse("image/*"), new File(Cache.FACE_MODULE + File.separator + ID_CARD_FRONT)))
                .addFormDataPart("files", backName, RequestBody.create(MediaType.parse("image/*"), new File(Cache.FACE_MODULE + File.separator + ID_CARD_BACK)))
                .addFormDataPart("files", faceName, RequestBody.create(MediaType.parse("image/*"), new File(Cache.FACE_MODULE + File.separator + FACE_PHOTOS)))
                .build();
        httpManagerUtils.post(HttpURL.BASE_URL + HttpURL.saveBusiLoanInfoByIdCheck, requestBody, new BaseRespCallBack() {
            @Override
            public void onRespSuccess(String respStr) {
                showTip("人脸信息上传成功");
                showImage(FACE);
                imageButtonIDCardPositive.setOnClickListener(null);
                imageButtonIDCardReverse.setOnClickListener(null);
                imageButtonHeadPortrait.setOnClickListener(null);
                iv_lock.setVisibility(View.GONE);
                ((DocumentsReviewActivity) getActivity()).setUploadSuccess(true);
                if(mPageType == DocumentsReviewActivity.MAIN_TYPE) {
                    ((DocumentsReviewActivity)getActivity()).setMainFinish(true);
                }
            }

            @Override
            public void onRespFailure(String msg) {
                super.onRespFailure(msg);
                ToastUtils.showToast(msg);
                if(mPageType == DocumentsReviewActivity.MAIN_TYPE) {
                    ((DocumentsReviewActivity)getActivity()).setMainFinish(false);
                }
            }
        });

    }

    private void doPlay(int rawId) {
        if (mMediaPlayer == null) {
            mMediaPlayer = new MediaPlayer();
        }

        mMediaPlayer.reset();
        try {
            AssetFileDescriptor localAssetFileDescriptor = getResources().openRawResourceFd(rawId);
            mMediaPlayer.setDataSource(
                    localAssetFileDescriptor.getFileDescriptor(),
                    localAssetFileDescriptor.getStartOffset(),
                    localAssetFileDescriptor.getLength());
            mMediaPlayer.prepare();
            mMediaPlayer.start();
        } catch (Exception localIOException) {
            localIOException.printStackTrace();
        }
    }

    /*******************************************人脸识别 End********************************************/

    @Override
    public void onClick(String name, String idCard) {
        if (TextUtils.isEmpty(name) && TextUtils.isEmpty(idCard)) {
            //对话框关闭标志
            iv_lock.setImageResource(R.mipmap.lock_close);
        } else {
            clientName = name;
            doFaceVerify();
        }
    }

    /**
     * 描述:人脸识别失败，提示修改name，idcard弹框
     */
    private void showDialog() {
        IdCardDialog dialog = new IdCardDialog(getContext(), this, clientName, idCard);
        dialog.show();
        iv_lock.setImageResource(R.mipmap.lock_open);
    }

    public void setType(int type) {
        mPageType = type;
    }

}

